Skip to main content

How to detect touching a 3D object in the scene and change its texture

⚠️ for it to work correctly, the object must have some type of collision ⚠️

In your Java class, do the following:

public class YourClass extends Component {

// creates a new texture
public Texture texture; // select in properties

// creates a new Laser
private final Laser laser = new Laser();

// creates a new Camera, @Singleton attaches the first Camera component it finds in the scene
@Singleton
private Camera camera;

@Override
public void start() {

}

@Override
public void repeat() {

// checking whether the first touch detected on the screen is null and returning the code if it is true
if(Input.getTouch(0) == null) return;

// Vector2 responsible for storing the position of the first touch detected on the screen
Vector2 position = Input.getTouch(0).getPosition();

// the direction of the ray that will be fired from the camera at the position of the "position" variable
RayDirection rayDirection = camera.screenPointRay(position);

// the ray that will be fired
Ray ray = new Ray(rayDirection, 0);

// the laser collision point
LaserHit laserHit = laser.trace(ray);

// checking if laserHit is non-null
if(laserHit != null) {

// fetching the ModelRenderer of the object that laserHit detected
ModelRenderer modelRenderer = lasetHit.getObject().findComponent(ModelRenderer.class);

// checking if ModelRenderer is non-null
if(modelRenderer != null) {

// changing the texture of the object's ModelRenderer
modelRenderer.getMaterial().setTexture("albedo", texture);
}
}
}
}